package kiwi.assist.dev.guieditor.command {
	import fl.core.UIComponent;

	import ghostcat.util.ReflectUtil;

	import kiwi.assist.dev.guieditor.event.GUIEditorEvent;
	import kiwi.assist.dev.guieditor.event.GUIOperateEvent;
	import kiwi.assist.dev.guieditor.model.ContainerConfig;
	import kiwi.assist.dev.guieditor.model.GUIEditorConfig;
	import kiwi.assist.dev.guieditor.model.UiConfig;
	import kiwi.assist.dev.guieditor.model.UiDetailVO;
	import kiwi.assist.dev.reflect.FlashUiComponentReflectFactoryImpl;
	import kiwi.assist.dev.reflect.IReflectFactory;
	import kiwi.assist.dev.util.SkinComponentAdapter;
	import kiwi.debug.Log;

	import org.robotlegs.mvcs.Command;

	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;

	/**
	 * @author zhangming.luo
	 */
	public class LoadUiCommand extends Command {
		[Inject]
		public var detail : UiDetailVO;
		[Inject]
		public var config : GUIEditorConfig;
		[Inject]
		public var event : GUIEditorEvent;
		private var xml : XML;

		override public function execute() : void {
			super.execute();
			var file : File;
			try {
				if (event.data) {
					file = File.applicationDirectory.resolvePath(event.data);
					var input : FileStream = new FileStream();
					input.open(file, FileMode.READ);
					var bytes : ByteArray = new ByteArray();
					input.readBytes(bytes, 0, file.size);
					input.close();
					rebuild(String(bytes));
					detail.name = file.name.replace(".ui", "");
					detail.projectPath = file.parent.nativePath;
				} else {
					file = new File();
					file.addEventListener(Event.SELECT, function() : void {
						file.addEventListener(Event.COMPLETE, function() : void {
							rebuild(String(file.data));
							detail.name = file.name.replace(".ui", "");
							detail.projectPath = file.parent.nativePath;
						});
						file.load();
					});
					file.browse([new FileFilter("*.ui", "*.ui")]);
				}
				// 由于ui都是Calllater的刷新所以需要等等
				setTimeout(onComplete, 1000);
			} catch(e : Error) {
				Log.error("加载失败了" + file.nativePath, e);
			}
		}

		private function onComplete() : void {
			dispatch(new GUIEditorEvent(GUIEditorEvent.BUILD_COMPLETE));
		}

		private function rebuild(data : String) : void {
			dispatch(new GUIEditorEvent(GUIEditorEvent.NEW_PROJECT));
			xml = new XML(data);
			rebuildContainer();
			rebuildBackground();
			rebuildUi();
		}

		private function rebuildUi() : void {
			for each (var ui:XML in xml.uis.ui) {
				var comp : String = XML(ui.@comp).toString();
				if (!comp) {
					continue;
				}
				var uiConfig : UiConfig = config.getUiConfigByComp(comp);
				if (!uiConfig) {
					Log.warn("有个控件找不到了" + comp);
					continue;
				}
				var dos : DisplayObject = newComponent(uiConfig, XML(ui.children()));
				dispatch(new GUIOperateEvent(GUIOperateEvent.UI_ADD, dos));
			}
		}

		private function rebuildBackground() : void {
			for each (var background:XML in xml.background.children()) {
				var dos : SkinComponentAdapter = new SkinComponentAdapter(config.getSkinByName(background.localName()), config.uiPrefix);
				dos.x = int(XML(background.x));
				dos.y = int(XML(background.y));
				dos.width = int(XML(background.width));
				dos.height = int(XML(background.height));
				if (background.child("name").length() > 0) {
					dos.name = XML(background.name).text();
				}
				dispatch(new GUIOperateEvent(GUIOperateEvent.BACKGROUND_ADD, dos));
			}
		}

		private function rebuildContainer() : void {
			if (XML(xml.container).children().length() == 0) {
				return;
			}
			var containerXML : XML = XML(xml.container.ui.children());
			var comp : String = XML(xml.container.ui.@comp).toString();
			if (!comp) {
				return;
			}
			var containerConfig : ContainerConfig = ContainerConfig(config.getUiConfigByComp(comp));
			if (!containerConfig) {
				return;
			}
			detail.container = containerConfig;
			var dos : UIComponent = UIComponent(newComponent(containerConfig, containerXML));
			detail.containerImpl = dos;
			detail.containerImpl.mouseEnabled = false;
			detail.containerImpl.mouseChildren = false;
			containerConfig.instanceMap[dos] = true;
			dispatch(new GUIEditorEvent(GUIEditorEvent.CONTAINER_CHANGE, dos));
		}

		private function newComponent(comp : UiConfig, defaultConfig : XML) : DisplayObject {
			var factory : IReflectFactory;
			if (comp.factoryClz) {
				// 有工厂的
				factory = injector.instantiate(ReflectUtil.getClass(comp.factoryClz));
			} else {
				// 走默认工厂
				factory = injector.instantiate(FlashUiComponentReflectFactoryImpl);
			}
			var dos : DisplayObject = DisplayObject(factory.newInstance(defaultConfig));
			comp.instanceMap[dos] = true;
			detail.uiList.push(dos);
			detail.configList[dos] = comp;
			return dos;
		}
	}
}
